<template >
    <!--<label for="file" class="excelBtn">Excel导入</label>
         <input type="file" id="file" ref="myfile" style="display:none" >
    <el-button type="primary" icon="el-icon-upload2" @click="submit()" class="searchItem">手动提交文件
    </el-button> -->
    <el-upload 
        class="upload"
        :action="apiHost"
        :ref="file"
        :data="data"
        :show-file-list="showFileList"
        :auto-upload="autoUpload"
        :headers='token'
        :with-credentials="withCredentials"
        :drag="drag"
        :multiple="multiple"
        :limit="limit"
        :disabled="isDisabled"
        :on-success="uploadSuccess"
        :before-upload="beforeUpload"
        :on-progress="onUpload"
        >
        <!-- 
        accept="*"
        :accept="accept"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :on-change="changeFile"
        :on-error="error"
        :before-remove="beforeRemove"
        <el-button size="middle" type="primary" icon="el-icon-upload2">上传文件</el-button> -->
        <div v-if="drag == false">
            <el-button  :size="size" :type="type" :icon="icon">上传文件</el-button>
        </div>
        <div v-else-if="drag == true">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </div>
        
        <div slot="tip" class="el-upload__tip">只能上传{{accept}}文件,文件大小不超过{{limitSize}}M</div>
    </el-upload>
</template>
<script>
import { apiHost } from '@/services/axiosInterceptor';
import servicesApi from '@/services/servicesApi';
import debounce from 'lodash/debounce';
import storageService from '@/store/storage';
export default {
    name: 'fileDown',
    data() {
        return {
            apiHost: '',
            file: null,
            token: {
                csrftoken: storageService.getToken()
            },
            isDisabled: false, //上传中禁用上传
        }
    },
    props: {
        url: { //接口路径
            type: [String, String, Boolean, Number, Object],
            required: true,
            default: '/student/wenxian'
        },
        size: {
            type: [String],
            required: false,
            default: 'middle'
        },
        type: {
            type: [String],
            required: false,
            default: 'primary'
        },
        icon: {
            type: [String],
            required: false,
            default: 'el-icon-upload'
        },
        showFileList: { //是否显示已上传文件列表
            type: [Boolean],
            required: false,
            default: true
        },
        accept: { //接受上传的文件类型
            type: [String],
            required: false,
            default: 'docx,txt,doc,pdf,doc,xls'
        },
        autoUpload: { //是否在选取文件后立即进行上传
            type: [Boolean],
            required: false,
            default: true
        },
        withCredentials: { //支持发送 cookie 凭证信息
            type: [Boolean],
            required: false,
            default: true
        },
        multiple: { //是否支持多选文件
            type: [Boolean],
            required: false,
            default: true
        },
        drag: { //是否启用拖拽上传
            type: [Boolean],
            required: false,
            default: true
        },
        limit: { //最大允许上传个数
            type: [String, Boolean, Number],
            required: false,
            default: 3
        },
        limitSize: { //最大允许上传大小
            type: [String, Number],
            required: false,
            default: 100
        },
        data: { //上传时附带的额外参数
            type: [Object],
            required: false,
            default: function() {
                return {}
            }
        },
    },
    created() {
        this.apiHost = apiHost + this.url
        // console.log('created子组件', this.apiHost);
    },
    mounted() {
        // console.log('子组件', this.FileInfo);
    },
    
    methods: {
        onUpload(e, file, fileList) {
            this.isDisabled = true 
        },
        uploadSuccess(res, file, fileList) {
            // console.log(file)
            // console.log(`======${file.name}文件上传成功=====`)
            this.isDisabled = false
            if (res.code === 200) {
                this.$message.success('上传成功');
                // this.getDataList(); //刷新页面
                setTimeout(() => {
                    this.$emit('submitToParent')
                }, 500)
            }
            else {
                // console.log(res)
                this.$message.error(res.msg);
            }
        },
        changeFile(val) {
            // console.log('选择文件成功');
            this.file = val.raw;
            // console.log(val)
            // console.log(this.file)
            // let nameArray = val.name.split(".");
            // if (nameArray[nameArray.length - 1] === "xlsx") {
            //     // file保存选择的文件
            //     this.file = val.raw;
            // } else {
            //     this.$message({
            //         message: '表格格式错误,请确认表格内容并重新上传',
            //         type: 'warning',
            //         duration: 2000
            //     });
            // }
        },
        
        handleRemove(file, fileList) {
            // console.log(file, fileList);
            return this.$confirm(`确定移除 ${file.name}?`);
        },
        handlePreview(file) {
            // console.log(file);
        },
        handleExceed(files, fileList) { //文件数量超出限制的钩子
            this.$message.warning(`当前限制选择${this.limit}个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeUpload(file) { //文件上传前的校验
            // console.log(file)
            const typeList = ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain', 'application/msword', 'application/pdf', 'application/vnd.ms-excel'];
            // const FileType = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
            const size = this.limitSize;
            let FileType = false;
            const isLt = file.size / 1024 / 1024 < size;
            if (typeList.includes(file.type)) {
                // console.log('上传文件类型正确')
                FileType = true;
            }
            if (!FileType) {
                this.$message.error('上传文件格式错误!');
            }
            if (!isLt) {
                this.$message.error(`上传文件大小不能超过${size}MB!`);
            }
            return FileType && isLt;
        },
        beforeRemove(file, fileList) { //文件移除前的钩子
            return this.$confirm(`移除 ${file.name}?`);
        },


        submit() { //手动上传
            // // console.log("提交");
            let myfile = this.$refs.myfile;
            let files = myfile.files;
            this.file = files[0];
            let formData = new FormData();
            formData.append('file', this.file);
            // 添加其他非文件的参数，可以使用set() 方法
            // formData.set('config_type', this.json.config_typ);
            this.loading = true;
            // 接口里面需要指定请求头 headers['Content-Type'] = 'multipart/form-data'
            servicesApi.submitWenxian(formData).then(res => {
                if (res.data.code === 200) {
                    this.$message({
                        message: '操作成功',
                        type: 'success',
                        duration: 500,
                    });
                }
                else {
                    this.$message.error(res.data.msg);
                }
            });
        },
    }

}
</script>
<style scoped>
.upload{
    margin: 10px 0px;
}
</style>